import CryptoJS from 'crypto-js'

/*
 * @Description  : 工具函数
 * @Autor        : Liuqingbo
 * @Date         : 2020-08-18 10:18:26
 * @LastEditors  : wty
 * @LastEditTime : 2022-02-23 09:52:45
 * @FilePath     : \src\common\units.js
 */
/**
 *
 * @param {String} sHex
 * @param {Number} alpha
 */
function color2Rgba(sHex, alpha = 1) {
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  /* 16进制颜色转为RGB格式 */
  let sColor = sHex.toLowerCase()
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = '#'
      for (let i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
      }
      sColor = sColorNew
    }
    //  处理六位的颜色值
    var sColorChange = []
    for (let i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
    }
    // return sColorChange.join(',')
    // 或
    return 'rgba(' + sColorChange.join(',') + ',' + alpha + ')'
  } else {
    return sColor
  }
}

/**
 * desc: base64对象转blob文件对象
 * @param urlData  ：数据的base64对象
 * @param type  ：类型 png,pdf,doc,mp3等;
 * @returns {Blob}：Blob文件对象
 */
function base64ToBlob(urlData, type) {
  let arr = urlData.split(',')
  let array = arr[0].match(/:(.*?);/)
  let mime = (array && array.length > 1 ? array[1] : type) || type
  // 去掉url的头，并转化为byte
  let bytes = window.atob(arr[1])
  // 处理异常,将ascii码小于0的转换为大于0
  let ab = new ArrayBuffer(bytes.length)
  // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
  let ia = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new Blob([ab], {
    type: mime,
  })
}

// 压缩图片
function compressImage(path) {
  //最大高度
  const maxHeight = 500
  //最大宽度
  const maxWidth = 500

  return new Promise((resolve, reject) => {
    let img = new Image()
    img.src = path

    console.log(img, 'pathpath')
    img.onload = function () {
      const originHeight = img.height
      const originWidth = img.width
      let compressedWidth = img.height
      let compressedHeight = img.width
      if (originWidth > maxWidth && originHeight > maxHeight) {
        // 更宽更高，
        if (originHeight / originWidth > maxHeight / maxWidth) {
          // 更加严重的高窄型，确定最大高，压缩宽度
          compressedHeight = maxHeight
          compressedWidth = maxHeight * (originWidth / originHeight)
        } else {
          //更加严重的矮宽型, 确定最大宽，压缩高度
          compressedWidth = maxWidth
          compressedHeight = maxWidth * (originHeight / originWidth)
        }
      } else if (originWidth > maxWidth && originHeight <= maxHeight) {
        // 更宽，但比较矮，以maxWidth作为基准
        compressedWidth = maxWidth
        compressedHeight = maxWidth * (originHeight / originWidth)
      } else if (originWidth <= maxWidth && originHeight > maxHeight) {
        // 比较窄，但很高，取maxHight为基准
        compressedHeight = maxHeight
        compressedWidth = maxHeight * (originWidth / originHeight)
      } else {
        // 符合宽高限制，不做压缩
      }
      // 生成canvas
      let canvas = document.createElement('canvas')
      let context = canvas.getContext('2d')
      canvas.height = compressedHeight
      canvas.width = compressedWidth
      context.clearRect(0, 0, compressedWidth, compressedHeight)
      context.drawImage(img, 0, 0, compressedWidth, compressedHeight)
      let base64 = canvas.toDataURL('image/*', 0.8)
      let blob = base64ToBlob(base64)
      // 回调函数返回blob的值。也可根据自己的需求返回base64的值
      resolve(blob)
    }
  })
}

function timestampToDateTime(timestamp = Date.now(), format = 'yyyy-MM') {
  if (isNaN(timestamp)) {
    return ''
  }
  if (format.length < 4 || 'yyyy-MM-dd HH:mm:ss'.indexOf(format) !== 0) {
    return ''
  }
  const date = new Date(Number(timestamp))
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return format
    .replace('yyyy', year)
    .replace('MM', month > 9 ? month : `0${month}`)
    .replace('dd', day > 9 ? day : `0${day}`)
    .replace('HH', hour > 9 ? hour : `0${hour}`)
    .replace('mm', minute > 9 ? minute : `0${minute}`)
    .replace('ss', second > 9 ? second : `0${second}`)
}

function toUint8Array(wordArray) {
  // Shortcuts
  const words = wordArray.words
  const sigBytes = wordArray.sigBytes

  // Convert
  const u8 = new Uint8Array(sigBytes)
  for (let i = 0; i < sigBytes; i++) {
    u8[i] = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff
  }
  return u8
}

function Uint8ArrayToString(fileData) {
  let dataString = ''
  for (let i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i])
  }
  return dataString
}
// 签名函数示例
function signCallback(signStr) {
  const secretKey = config.secretKey
  const hash = CryptoJS.HmacSHA1(signStr, secretKey)
  const bytes = Uint8ArrayToString(toUint8Array(hash))
  return window.btoa(bytes)
}
//加密
function smEncrypt(dataObj) {
  var sm2 = require('sm-crypto').sm2
  let cipherMode = 1 // 1 - C1C3C2，0 - C1C2C3，默认为1
  let msg = dataObj
  if (typeof dataObj != 'string') {
    msg = JSON.stringify(dataObj)
  }
  return sm2.doEncrypt(msg, config.publicKey, cipherMode) // 加密结果
}
export { color2Rgba, base64ToBlob, compressImage, timestampToDateTime, signCallback, smEncrypt }
